package com.hancher.common.androidutil;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresApi;

import com.hancher.common.javautil.FileUtil;
import com.hancher.common.javautil.UuidUtil;
import com.hancher.plugins.hrlog.HrLogUtil;

import java.io.File;

public class IntentUtil {

    public static final String TYPE_IMAGE = "image/*";

    public static class SelectFileBuilder {
        private File selectDir;
        private View clickView;
        private String selectType;
        private ComponentActivity activity;
        private ActivityResultLauncher<String> selectLauncher;
        private ActivityResultCallback<File> callback;

        public String getSelectType() {
            return selectType;
        }

        public SelectFileBuilder setSelectType(String selectType) {
            this.selectType = selectType;
            return this;
        }

        public ActivityResultCallback<File> getCallback() {
            return callback;
        }

        public SelectFileBuilder setCallback(ActivityResultCallback<File> callback) {
            this.callback = callback;
            return this;
        }

        public ComponentActivity getActivity() {
            return activity;
        }

        public SelectFileBuilder setActivity(ComponentActivity activity) {
            this.activity = activity;
            return this;
        }

        public File getSelectDir() {
            return selectDir;
        }

        public SelectFileBuilder setSelectDir(File selectDir) {
            this.selectDir = selectDir;
            return this;
        }

        public View getClickView() {
            return clickView;
        }

        public SelectFileBuilder setClickView(View clickView) {
            this.clickView = clickView;
            return this;
        }

        public ActivityResultLauncher<String> build() {
            selectLauncher = activity.registerForActivityResult(new ActivityResultContracts.GetContent(), result -> {
                String oldFile = UriUtil.getPathByUri(activity, result);
                if (TextUtils.isEmpty(oldFile)) {
                    HrLogUtil.w("选择文件解析失败");
                    callback.onActivityResult(null);
                    return;
                }
                File imageFile = new File(selectDir.getParent(), UuidUtil.getUuidNoLine() + oldFile.substring(oldFile.lastIndexOf(".")));
                boolean result2 = FileUtil.copyFile2File(new File(oldFile), imageFile);
                if (result2) {
                    callback.onActivityResult(imageFile);
                } else {
                    HrLogUtil.w("选择文件复制失败");
                    callback.onActivityResult(null);
                }
            });
            if (clickView != null) {
                clickView.setOnClickListener(view -> selectLauncher.launch(selectType));
            } else {
                selectLauncher.launch(selectType);
            }
            return selectLauncher;
        }
    }

    public static class TakePictureBuilder {
        private File pictureDir;
        private File pictureFile;
        private View clickView;
        private ComponentActivity activity;
        private ActivityResultLauncher<Uri> launcher;
        private ActivityResultCallback<File> callback;
        private Uri uri;

        public Uri getUri() {
            return uri;
        }

        public TakePictureBuilder setUri(Uri uri) {
            this.uri = uri;
            return this;
        }

        public ActivityResultCallback<File> getCallback() {
            return callback;
        }

        public TakePictureBuilder setCallback(ActivityResultCallback<File> callback) {
            this.callback = callback;
            return this;
        }

        public ComponentActivity getActivity() {
            return activity;
        }

        public TakePictureBuilder setActivity(ComponentActivity activity) {
            this.activity = activity;
            return this;
        }

        public File getPictureDir() {
            return pictureDir;
        }

        public TakePictureBuilder setPictureDir(File pictureDir) {
            this.pictureDir = pictureDir;
            return this;
        }

        public View getClickView() {
            return clickView;
        }

        public TakePictureBuilder setClickView(View clickView) {
            this.clickView = clickView;
            return this;
        }

        public ActivityResultLauncher<Uri> build() {
            launcher = activity.registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
                HrLogUtil.d("拍摄进度");
                if (result) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        FileUtil.copyFile2File(new File(PathUtil.OUT_PUBLIC_PICTURES, pictureFile.getName()), pictureFile);
                    }
                    callback.onActivityResult(pictureFile);
                } else {
                    callback.onActivityResult(null);
                }
            });
            pictureFile = new File(pictureDir, UuidUtil.getUuidNoLine() + ".jpg");
            uri = UriUtil.getUri(activity, pictureFile, true);
            if (clickView != null) {
                clickView.setOnClickListener(view -> {
                    launcher.launch(uri);
                });
            } else {
                launcher.launch(uri);
            }
            return launcher;
        }
    }

    /**
     * 使用已安装的文件选择器
     *
     * @return
     */
    public static Intent getSelectFileIntent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        return Intent.createChooser(intent, "选择一个文件");
    }
    /*
    startActivityForResult(IntentUtil.getSelectFileIntent(), CommonConfig.REQUEST_CODE_FILE_SELECT);

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CommonConfig.REQUEST_CODE_FILE_SELECT:
                if (resultCode == RESULT_OK) {
                    UriUtil.getPathByUri(this, data.getData());
                }
                break;
        }
        presenter.startRecover();
    }
     */


    /**
     * 文件分享页面
     *
     * @param context
     * @param file
     * @return
     */
    public static Intent getShareFileIntent(Context context, File file) {
        if (file == null || !file.exists()) {
            ToastUtil.show("分享文件不存在：" + file.getAbsolutePath());
            return null;
        }
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        Intent share = new Intent(Intent.ACTION_SEND);
        share.putExtra(Intent.EXTRA_STREAM, UriUtil.getUri(context, file));
        share.setType(UriUtil.getMimeType(file.getAbsolutePath()));//此处可发送多种文件
        share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return Intent.createChooser(share, "分享文件");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static Intent getInstallPermission(Context context) {
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        return new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
    }

    /**
     * 获取安装apk的Intent
     *
     * @param context
     * @param file
     * @return
     */
    public static Intent getInstallIntent(Context context, File file) {
        if (file == null || !file.exists()) {
            ToastUtil.show("分享文件不存在");
            return null;
        }
        Intent install = new Intent();
        install.setAction(Intent.ACTION_VIEW);
        install.addCategory(Intent.CATEGORY_DEFAULT);
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//        install.setDataAndType("content://Uri","appplication/vnd.android.package-archive");
        install.setDataAndType(UriUtil.getUri(context, file), UriUtil.getMimeType(file.getAbsolutePath()));
        return install;
    }

    public static Intent getHomeIntent() {
        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
        homeIntent.addCategory(Intent.CATEGORY_HOME);
        return homeIntent;
    }
}